from keras.datasets import mnist
from keras import models
from keras import layers
from keras.utils import to_categorical
import matplotlib.pyplot as plt

(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

# 创建神经网络模型的“模型对象”
model = models.Sequential()
# 定义神经网络模型的输入层（也即是第0层）
model.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
# 这层是输出层，输出的节点是10个，并且输出层使用了softmax激活函数
model.add(layers.Dense(10, activation='softmax'))
# 通过summary查询我这个模型的结构是什么样的？
# 编译神经网络模型，设置“优化器、损失函数、在训练和测试过程中需要监控的指标（metric）”
model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

train_images = train_images.reshape((60000, 28 * 28))
print(train_images[0].shape)  # (784,)
print(train_images[0])

train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255
print(train_labels[0])  # 5
train_labels = to_categorical(train_labels)
print(train_labels[0])  # [ 0.  0.  0.  0.  0.  1.  0.  0.  0.  0.]
print(train_labels.dtype)
test_labels = to_categorical(test_labels)

# ----------开始训练模型------------------
model.fit(train_images, train_labels, epochs=5, batch_size=128)
# ----------通过“测试”数据集评估模型的“性能/泛化能力”------------------
test_loss, test_acc = model.evaluate(test_images, test_labels)
print("-" * 50)
print('test_loss:', test_loss)
print('test_acc:', test_acc)
